package com.googlecode.puddle;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.googlecode.puddle.data.Podcast;
import com.googlecode.puddle.data.PuddleDbAdapter;
import com.googlecode.puddle.data.Show;
import com.googlecode.puddle.reader.PodcastFeedReader;

public class AddPodcast extends Activity {
	private static final String TAG = AddPodcast.class.getName();
	
	private PuddleDbAdapter podcastDb;
	private Button addPodcastButton;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "Setting up Add Podcast activity");
		setContentView(R.layout.add_podcast);

		podcastDb = new PuddleDbAdapter(this);
		podcastDb.open();
		
		addPodcastButton = (Button) findViewById(R.id.AddPodcastButton);
		addPodcastButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				EditText urlText = (EditText) findViewById(R.id.AddPodcastUrl);
				String url = urlText.getText().toString();
				addPodcast(url);
			}
		});
	}
	
	@Override
	protected void onDestroy() {
		podcastDb.close();
		super.onDestroy();
	}

	public void addPodcast(String url) {
		Log.i(TAG, "Adding podcast at URL: " + url);
		Podcast podcast = PodcastFeedReader.readPodcastFromUrl(url);
		
		long podcastId = podcastDb.createPodcast(podcast.getTitle(), podcast.getDescription(), podcast.getUrl());
		for (Show s : podcast.getShows()) {
			podcastDb.addShow(podcastId, s.getTitle(), s.getDescription(), s.getUrl(), s.getDate());
		}
		setResult(RESULT_OK);
		finish();
	}
	
	
}